import React from "react";
import { useState, useEffect } from "react";
import { PageHeader, TypeSelect } from "@/components";
import { getBookByPage } from "@/api/book";
import { Card, Empty, Pagination } from "antd";
import styles from "./Books.module.css";
import { useNavigate } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
export default function Books() {
  const [booksInfo, setBooksInfo] = useState([]);
  const [pageInfo, setPageInfo] = useState({
    current: 1,
    pageSize: 15,
    total: 0,
  });
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { bookTypeId } = useSelector((state) => state.type);

  useEffect(() => {
    async function fetchData() {
      let searchParams = {
        current: pageInfo.current,
        pageSize: pageInfo.pageSize,
      };

      if (bookTypeId !== "all") {
        searchParams.typeId = bookTypeId;
      }

      const { data } = await getBookByPage(searchParams);

      setBooksInfo(data.data);
      setPageInfo({
        current: data.currentPage,
        pageSize: data.eachPage,
        total: data.count,
      });
    }
    fetchData();
  }, [pageInfo.current, pageInfo.pageSize, bookTypeId]);

  const handlePageChange = (current, pageSize) => {
    setPageInfo({
      current,
      pageSize,
    });
  };

  return (
    <>
      <div>
        <PageHeader title="精选书籍">
          <TypeSelect />
        </PageHeader>
        <div className={styles.bookContainer}>
          {
            // 渲染每一本书
            booksInfo.length > 0 ? (
              <>
                {booksInfo.map((book) => (
                  <Card
                    onClick={() => navigate(`/book/id=${book._id}`)}
                    key={book._id}
                    hoverable
                    style={{
                      width: 200,
                      marginBottom: 30,
                    }}
                    cover={
                      <img
                        alt="example"
                        style={{
                          width: 160,
                          height: 200,
                          margin: "auto",
                          marginTop: 10,
                        }}
                        src={book.bookPic}
                      />
                    }
                  >
                    <Card.Meta title={book.bookTitle} />
                    <div className={styles.numberContainer}>
                      <div>浏览数：{book.scanNumber}</div>
                      <div>评论数：{book.commentNumber}</div>
                    </div>
                  </Card>
                ))}
                <div className={styles.paginationContainer}>
                  <Pagination showQuickJumper {...pageInfo} onChange={handlePageChange} />
                </div>
              </>
            ) : (
              <Empty style={{ margin: "10px auto" }} />
            )
          }
        </div>
      </div>
    </>
  );
}
